package backstage.sys.listener;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import backstage.sys.util.Platform;

public class PlatformLoader {
	
	private ContextLoader contextLoader;

	public void init(ServletContext context) {
		if (context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
					"Cannot initialize context because there is already a root application context present - " +
					"check whether you have multiple ContextLoader* definitions in your web.xml!");
		}
		initWebApplication(context);
	}
	
	private void initWebApplication(ServletContext context) {
		contextLoader = new ContextLoader();
		ApplicationContext web = (ApplicationContext) contextLoader.initWebApplicationContext(context);
		Platform.getInstance().setApplication(web);
	}

	public ContextLoader getContextLoader() {
		return contextLoader;
	}

	public void setContextLoader(ContextLoader contextLoader) {
		this.contextLoader = contextLoader;
	}
}
